
import updateView from './updateView.js'
export {
  checkVersion
}
 
function checkVersion() {
  //processing = true;
  // updateState(true)
  let versionLocal = null;
	let downloadUrl = '';
  plus.runtime.getProperty(plus.runtime.appid, function(info) {
    console.log("当前版本 " + info.version)
    versionLocal = info.version;
		console.log(22222);
    //检测升级
    uni.request({
      // url: 'https://haciend-aassets-5gdqxjj2b8cudbaseapp.com/app-assets/hotfix/version.txt?v=' +
      // 	new Date().getTime(), //检查更新的服务器地址
      url: 'http://124.70.9.55:19000/app-version/latest-version', //检查更新的服务器地址
      method: 'GET',
      success: (res) => {
        if (res.statusCode && res.statusCode == 200) { // api错误
          let item = null
          let infos = res.data.data;
					infos.versions = infos.versionCode;
					downloadUrl = infos.downloadUrl;
					console.log('downloadurl====', infos.downloadUrl);
          // console.log("versionLocal:", versionLocal)
          // console.log("info.versions.version:", info.versions[0].version)
          // for (let index = 0; index < info.versions.length; index++) {
          //   if (info.versions[index].version == versionLocal) {
          //     item = info.versions[index];
          //     break;
          //   }
          // }
					console.log('服务器版本----', infos.versions);
          if (infos.versions == versionLocal) {
            //processing = false;
            updateState(false)
            console.log("你已经是最新版本..")
          } else {
						console.log(compareVersion(versionLocal, infos.versions));
            //先判断大版本 //(versonHigh(versionLocal) <= versonHigh(info.versions)) || (versonLow(versionLocal) <= versonLow(info.versions))
            if (compareVersion(versionLocal, infos.versions)) {
              console.log("---------->大版本不同")
              // 更新软件
              if (uni.getSystemInfoSync().platform == 'android') {
                installAndroid(infos)
              } else if (uni.getSystemInfoSync().platform == 'ios') {
                uni.showModal({
                  title: '新版本提示',
                  content: '发现新的版本 点击确定更新！',
                  showCancel: false,
                  success: function(res) {
                    plus.runtime.openURL(infos.downlaodUrl);
                  }
                })
              }
              //判断小版本
            } 
						// else if (versonLow(versionLocal) != versonLow(info.versions)) {
      //         console.log("---------->小版本不同")
      //         // 更新资源 
      //         installAssets(info.versions)
      //       }
          }
        }
      },
      fail: (res) => {
        console.log("updateVersion Fail")
        updateState(false)
        // processing = false;
      }
    })
  })
 
 
}

/**
 * 比较两个版本号的大小
 * @param {string} v1 本地
 * @param {string} v2 服务器
 * @returns {0|1|-1} 0表示v1 = v2，1表示v1 > v2，-1表示v1 < v2
 *
 * compareVersion('1.1.0', '1.1.0');      // => false
 * compareVersion('1.20.0', '1.2.20');    // => false
 * compareVersion('v2.0.30', 'v1.9.10');  // => false
 * compareVersion('v1.1.40', 'v1.2.0');   // => true
 */
function compareVersion(v1, v2) {
  let cpResult;
  let i = 0;
  const arr1 = v1.replace(/[^0-9.]/, '').split('.');
  const arr2 = v2.replace(/[^0-9.]/, '').split('.');
  while (true) {
    const s1 = arr1[i];
    const s2 = arr2[i++];
    if (s1 === undefined || s2 === undefined) {
      cpResult = arr1.length - arr2.length;
      break;
    }
    if (s1 === s2) continue;
    cpResult = s1 - s2;
    break;
  }
  // eslint-disable-next-line
  return cpResult > 0 ? false : cpResult === 0 ? false : true;
}

function judgeVersion(oldV='', newV=''){
  let old=String(oldV).replace(/\./g, '');
  let ne=String(newV).replace(/\./g, '');
  return Number(ne)>Number(old);
}
//由于 IOS 版本只能三段 1.1.1
//大版本
function versonHigh(vers) {
  let arrayVers = vers.split('.')
  let versHigh = ''
  if (arrayVers.length == 3) {
    versHigh = arrayVers[0] + '.' + arrayVers[1]
  } else {
    //无效的版本信息
    console.log('获取大版本出错')
  }
  return versHigh
}
 
//小版本
function versonLow(vers) {
  let arrayVers = vers.split('.')
  let versLow = ''
  if (arrayVers.length == 3) {
    versLow = arrayVers[2]
  } else {
    //无效的版本信息
    console.log('获取小版本出错')
    updateState(false)
  }
  return versLow
}
 
function installAndroid(info) {
	try{
  updateView.viewHotFixInit();
	}catch(e){}
	console.log('downloadFile===', info.downloadUrl)
  uni.downloadFile({
    url: info.downloadUrl,
    complete: (res) => {
      updateView.viewHotFixHide()
      if (res && res.statusCode === 200) {
        plus.runtime.install(plus.io.convertLocalFileSystemURL(res.tempFilePath), {}, {}, function(error) {
          uni.showToast({
            title: '安装失败',
            icon: 'none',
            position: 'bottom',
            duration: 2000,
          });
          //processing = false;
          updateState(false)
        })
      } else {
        uni.showToast({
          title: '安装包下载失败',
          icon: 'none',
          position: 'bottom',
          duration: 2000,
        });
        // processing = false;
        updateState(false)
      }
    }
  }).onProgressUpdate((res) => {
    console.log('下载进度' + res.progress);
		// plus.nativeUI.toast("热更新中"+ res.progress);
		// plus.runtime.restart();
		try{
    updateView.viewHotFixUpdate(res.progress)
		}catch(e){}
  })
}
 
function installAssets(info) {
	try{
  updateView.viewHotFixInit();
	}catch(e){
		console.log(e);
	}
  uni.downloadFile({
    url: info.assets,
    complete: (res) => {
      //console.log("downloadFile: complete: (res)", res)
      updateView.viewHotFixHide()
      if (res && res.statusCode === 200) {
        plus.runtime.install(res.tempFilePath, {}, function(wgtinfo) {
          plus.nativeUI.alert("更新完成，需重启应用！", function() {
            plus.runtime.restart()
          });
        }, function(error) {
          uni.showToast({
            title: error ? error.message : '热刷新失败',
            icon: 'none',
            position: 'bottom',
            duration: 2000,
          });
          //processing = false;
          updateState(false)
        });
      } else {
        uni.showToast({
          title: '资源下载失败',
          icon: 'none',
          position: 'bottom',
          duration: 2000,
        });
        //processing = false;
        updateState(false)
      }
 
 
    }
  }).onProgressUpdate((res) => {
    // this.processText = res.progress
    //console.log('下载进度' + res.progress);
		try{
    updateView.viewHotFixUpdate(res.progress)
		}catch(e){
			console.log(e);
		}
  })
 
}
 
function updateState(value) {
  console.log("updateState:", value)
  // if (store) {
  //   store.commit('indexCore/setCheckState', value)
  // }
}